import Vue from 'vue'
import VueRouter from 'vue-router'

// 全局前置守卫
/*
  to：   去哪
  from： 从哪来
  to和from都是一个对象，里面路由的相关信息
  next： 是一个函数，调用它就代表放行，不调用就不放行
        next('别的路径') 放行到别的路径
        this.$router.push()可以怎么用，next就可以怎么用
    next({
      name: 'login',
      query: {
        name: 'jack',
        age: 16
      }
    })
*/
import { getToken } from '@/utils/token'
import { Toast } from 'vant'
// // 导入 - 如果是js文件、vue文件可以省略不写后缀
// import detail from '@/views/detail'
// import layout from '@/views/layout'
// import login from '@/views/login'
// import register from '@/views/register'
// // 导入二级路由
// import article from '@/views/article'
// import collect from '@/views/collect'
// import like from '@/views/like'
// import user from '@/views/user'

// -------------- 以下使用路由懒加载 -----------------
const detail = () => import('@/views/detail')
const layout = () => import('@/views/layout')
const login = () => import('@/views/login')
const register = () => import('@/views/register')
// 导入二级路由
const article = () => import('@/views/article')
const collect = () => import('@/views/collect')
const like = () => import('@/views/like')
const user = () => import('@/views/user')

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)
// 路由规则
const routes = [
  { path: '/', redirect: '/article' },
  {
    name: 'layout',
    path: '/',
    component: layout,
    children: [
      { name: 'article', path: 'article', component: article },
      { name: 'collect', path: 'collect', component: collect },
      { name: 'like', path: 'like', component: like },
      { name: 'user', path: 'user', component: user }
    ]
  },
  { name: 'detail', path: '/detail/:id', component: detail },
  { name: 'login', path: '/login', component: login },
  { name: 'register', path: '/register', component: register }
]

const router = new VueRouter({
  routes
})
// 保存白名单的数组
const whiteList = ['/login', '/register']
router.beforeEach((to, from, next) => {
  // 判断白名单里有没有包含我要去的路径
  // 包含代表在白名单里面
  if (whiteList.includes(to.path)) {
    next()
  } else {
    // 不在白名单里面就判断有没有登录
    if (getToken()) {
      // 代表有
      next()
    } else {
      // 请先登录
      Toast('请先登录')
      next('/login')
    }
  }
})

export default router
